package com.lkj.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author likanjia
 */
public class GroupChatServer {

    private Selector selector;

    private ServerSocketChannel listenChannel;


    public static final int PORT = 6667;

    public GroupChatServer() {

        try {
            selector = Selector.open();

            listenChannel = ServerSocketChannel.open();

            listenChannel.socket().bind(new InetSocketAddress(PORT));

            listenChannel.configureBlocking(false);

            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("服务器启动...");

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void listen() {
        try {

            while (true) {
                int select = selector.select();
                if (select > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();

                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();

                            socketChannel.configureBlocking(false);

                            socketChannel.register(selector,SelectionKey.OP_READ);

                            System.out.println(socketChannel.getRemoteAddress() + " 上线 ");
                        }

                        if (key.isReadable()) {
                            readData(key);
                        }

                        iterator.remove();

                    }
                } else {
                    System.out.println("等待连接......");
                }
            }

        } catch (Exception e){
            System.out.println("发生异常......");
            e.printStackTrace();
        } finally {
            System.out.println("发生异常....");
        }
    }

    private void readData(SelectionKey key) {
        SocketChannel channel = null;

        try {

            channel = (SocketChannel)key.channel();

            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int count = channel.read(buffer);

            if (count > 0) {
                String msg = new String(buffer.array());

                System.out.print("form 客户端："+msg);

                sendInfoToOtherClients(msg,channel);

            }

        } catch (Exception ex){

            try {
                System.out.println(channel.getRemoteAddress() +" 下线了");
                //取消注册
                key.cancel();

                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendInfoToOtherClients(String msg, SocketChannel channel) throws IOException {

        System.out.println("服务器转发消息中...");

        for (SelectionKey key : selector.keys()) {

            Channel targetChannel = key.channel();


            if (targetChannel instanceof SocketChannel && targetChannel != channel) {

                SocketChannel desc = (SocketChannel)targetChannel;

                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());

                desc.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();

    }
}

